<template>
  <div class="login-container">
    <div class="login-box">
      <h2>注册</h2>

      <!-- 注册表单 -->
      <form v-if="!isBindingEmail" @submit.prevent="handleRegister">
        <div class="input-group">
          <label for="username">用户名</label>
          <input v-model="username" type="text" id="username" placeholder="请输入用户名" required />
        </div>

        <div class="input-group">
          <label for="password">密码</label>
          <input
            v-model="password"
            type="password"
            id="password"
            placeholder="请输入密码"
            required
          />
        </div>

        <div class="input-group">
          <label for="email">邮箱</label>
          <input v-model="email" type="email" id="email" placeholder="请输入邮箱" required />
        </div>

        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>

        <div class="btn-group">
          <button type="submit" :disabled="isRegistering">
            {{ isRegistering ? '注册中...' : '注册' }}
          </button>
        </div>

        <div class="other-actions">
          <a @click.prevent="goToLogin" href="#">返回登录</a>
        </div>
      </form>

      <!-- 邮箱绑定部分 -->
      <div v-else>
        <p class="hint">已发送至 {{ email }}，请在 60 秒内输入：</p>

        <div class="input-group">
          <label for="code">验证码</label>
          <input v-model="code" type="text" id="code" placeholder="请输入验证码" required />
          <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
        </div>

        <div class="btn-row">
          <button id="submit-code-btn" :disabled="isVerifying" class="half-btn" @click="submitCode">
            提交验证码
          </button>

          <button
            class="half-btn"
            @click="resendCode"
            :disabled="countdown > 0"
            :class="{ 'disabled-btn': countdown > 0 }"
          >
            {{ countdown > 0 ? `${countdown}s 后可重发` : '重新发送验证码' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const email = ref('')
const code = ref('')
const errorMessage = ref('')
const isRegistering = ref(false)
const isBindingEmail = ref(false)
const isVerifying = ref(false)
const countdown = ref(60)
let timer: number | null = null

const router = useRouter()

// 倒计时函数
const startCountdown = () => {
  countdown.value = 60
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer!)
    }
  }, 1000)
}

// 注册提交
const handleRegister = async () => {
  errorMessage.value = ''
  isRegistering.value = true

  try {
    const response = await axios.post('/api/user/registerUserInfo', null, {
      params: {
        username: username.value,
        password: password.value,
        email: email.value,
      },
    })

    const res = response.data
    console.log('注册响应：', res)

    if (res === '账号可用，跳转到邮箱绑定' || res.message === '账号可用，跳转到邮箱绑定') {
      isBindingEmail.value = true
      startCountdown()

      await axios.post('/api/user/registerEmail', null, {
        params: {
          username: username.value,
          email: email.value,
          code: '',
        },
      })
    } else if (res === '账号已存在，请登录' || res.message === '账号已存在，请登录') {
      errorMessage.value = '账号已存在，请登录'
    } else {
      errorMessage.value = res.message || '系统异常'
    }
  } catch (err: unknown) {
    if (axios.isAxiosError(err)) {
      errorMessage.value = err.response?.data?.message || '请求失败，请检查网络'
    } else if (err instanceof Error) {
      errorMessage.value = err.message
    } else {
      errorMessage.value = '请求失败，请检查网络'
    }
  } finally {
    setTimeout(() => {
      isRegistering.value = false
    }, 400)
  }
}

// 提交验证码
const submitCode = async () => {
  isVerifying.value = true
  errorMessage.value = ''

  try {
    const response = await axios.post('/api/user/registerEmail', null, {
      params: {
        username: username.value,
        email: email.value,
        code: code.value,
      },
    })

    const res = response.data
    console.log('验证结果：', res)

    if (res === '注册成功' || res.message === '注册成功') {
      const btn = document.querySelector('#submit-code-btn') as HTMLButtonElement
      if (btn) btn.innerText = '注册成功'

      setTimeout(() => {
        router.push('/login')
      }, 400)
    } else {
      errorMessage.value = res.message || '验证码错误或已过期'
    }
  } catch (err: unknown) {
    if (axios.isAxiosError(err)) {
      if (err.response?.status === 401) {
        errorMessage.value = '验证码错误或已过期'
      } else {
        errorMessage.value = err.response?.data?.message || '请求失败，请检查网络'
      }
    } else if (err instanceof Error) {
      errorMessage.value = err.message
    } else {
      errorMessage.value = '请求失败，请检查网络'
    }
  } finally {
    setTimeout(() => {
      isVerifying.value = false
    }, 400)
  }
}

// 重新发送验证码
const resendCode = async () => {
  try {
    await axios.post('/api/user/registerEmail', null, {
      params: {
        username: username.value,
        email: email.value,
        code: '',
      },
    })
    startCountdown()
  } catch (err: unknown) {
    console.error('重新发送验证码失败：', err)
    errorMessage.value = '验证码发送失败，请稍后再试'
  }
}

// 跳转登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
}

.login-box {
  background: white;
  padding: 50px 40px;
  border-radius: 12px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 420px;
  box-sizing: border-box;
  text-align: center;
}

h2 {
  margin-bottom: 30px;
  font-size: 26px;
  font-weight: bold;
  color: #333;
}

.input-group {
  margin-bottom: 16px;
  text-align: left;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
}

.input-group input {
  width: 100%;
  padding: 14px 12px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-sizing: border-box;
}

.input-group input:focus {
  border-color: #409eff;
  outline: none;
}

.btn-group button,
.btn-row button {
  width: 100%;
  padding: 14px;
  background-color: #409eff;
  color: white;
  font-size: 18px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-group button:hover,
.btn-row button:hover {
  background-color: #2f8eff;
}

.btn-group button:disabled,
.btn-row button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.disabled-btn {
  background-color: #ccc !important;
  cursor: not-allowed !important;
}

.btn-row {
  display: flex;
  gap: 10px;
  margin-top: 16px;
}

.half-btn {
  width: 50%;
}

.hint {
  font-size: 13.5px;
  margin-bottom: 10px;
  color: #888;
  font-style: italic;
}

.error-message {
  color: #d9534f;
  margin-top: 6px;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s ease-in-out;
}

.other-actions {
  margin-top: 20px;
}

.other-actions a {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.other-actions a:hover {
  text-decoration: underline;
}
</style>
